#include "dList.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/*freeMem:
 *
 * author: Will Lamond -- edid Nathan Reimensnyder
 *
 * A linked list of structures to keep track of free memory.
 *
 */

/*add a node of free memory.  Supply the base and limit memory location of the process that
 *is being removed */

int addDNode(DISKLIST *list, int base, int end, int pid) {
	if (!list){
		printf("Uninitialized list in addDNode\n");
		return (-1);
	}
	DISKNODE *new = malloc(sizeof(DISKNODE));
	if (new) { //check to see if the malloc failed.
		DISKNODE *temp = list->head;
		new->pid = pid;
		new->base = base;
		new->end = end;
		new->size = (end - base);
		new->next = temp;
		list->head = new;
		printf("Successfully added a pager pages %d to %d\n", base, end);
		return 1;
	}
	return -1;
}

//removeNode: takes the base and limit values of a process and reorganizes free memory
int removeDNode(DISKLIST *list, int pid) {
	if (!list){
		printf("Uninitialized list in removeDNode\n");
		return (-1);
	}

	DISKNODE *temp = list->head;
	DISKNODE *last = NULL;
	//is the node we want to remove bounded by the head node?
	while (temp) {
		//is this the base you are looking for?
		if (temp->pid == pid) {
			//are they the same size?
				if (last) {
					last->next = temp->next;
				} else {
					list->head = temp->next;
				}
				printf("Successfully removed pager w/ pages %d to %d\n", temp->base, temp->end);
				free(temp);
				return 1;
		}
		//Not the correct node, so shift over by one.
		last = temp;
		temp = temp->next;
	}
	//return that an error occured.
	return -1;
}

/*initList: Initialize the Disk Memory list. */
int initDList(DISKLIST **newList) {
	*newList = malloc(sizeof(DISKLIST));
	if (*newList == NULL) {
		printf("Error allocating DiskList.\n");
		return -1;
	}

	(*newList)->head = NULL;
	return 1;
}

/* Return (1) on sucess the page node matching INPUT pid (pointed to by OUTPUT node)*/
int getPidPage(DISKLIST *list, DISKNODE * node, int pid) {
	if (!list || !node){
		printf("Uninitialized list/node in getPidPage\n");
		return (-1);
	}
	DISKNODE *temp = list->head;
	//is the node we want to remove bounded by the head node?
	while (temp) {
		//is this the base you are looking for?
		if (temp->pid == pid) {
			//are they the same size?
			*node = *temp;
			return 1;
		}
		//Not the correct node, so shift over by one.
		temp = temp->next;
	}
	//return that an error occured.
	return -1;
}



